package com.efast.cafe.portal.controller.company;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.event.Level;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.efast.cafe.commponent.log.ext.CafeLogger;
import com.efast.cafe.commponent.log.ext.CafeLoggerFactory;
import com.efast.cafe.framework.bean.ResultBean;
import com.efast.cafe.framework.bean.TResultBean;
import com.efast.cafe.framework.controller.AbstractController;
import com.efast.cafe.framework.enums.ResultStatus;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.json.JSONObject;
import com.efast.cafe.framework.pager.Pagination;
import com.efast.cafe.framework.util.SpringWebUtils;
import com.efast.cafe.portal.bean.company.PortalCompanyRoleAddUserBean;
import com.efast.cafe.portal.bean.company.PortalCompanyUserAddEditBean;
import com.efast.cafe.portal.bean.company.PortalCompanyUserBean;
import com.efast.cafe.portal.bean.company.PortalCompanyUserOrgPositionBean;
import com.efast.cafe.portal.bean.company.PortalCompanyUserQueryBean;
import com.efast.cafe.portal.bean.company.PortalCompanyUserRoleBean;
import com.efast.cafe.portal.entity.company.PortalCompanyRole;
import com.efast.cafe.portal.entity.company.PortalCompanyUser;
import com.efast.cafe.portal.entity.company.PortalCompanyUserReporttoTreeDto;
import com.efast.cafe.portal.service.company.IPortalCompanyPositionService;
import com.efast.cafe.portal.service.company.IPortalCompanyUserService;
import com.efast.cafe.util.StringUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/******************************************************************************
 * @File name : PortalCompanyUserCtroller.java
 *
 * @Author : xl
 *
 * @Date : 2016-6-12
 *
 * @Copyright Notice: Copyright (c) 2016 Efast Serv. All Rights Reserved. 公司用户管理
 * 
 * 
 *            ------------------------------------------------------------------
 *            ---------- Date Who Version Comments 2016-6-12 上午10:44:21 xl 1.0
 *            Initial Version
 *****************************************************************************/
@Api(description = "PortalCompanyUserController", tags = {"用户管理"})
@Controller
@RequestMapping("/company")
public class PortalCompanyUserController extends AbstractController {
	
	CafeLogger logger = CafeLoggerFactory.getLogger(PortalCompanyUserController.class);
	
	@Autowired
	private IPortalCompanyUserService portalCompanyUserService;

	
	@Autowired
	private IPortalCompanyPositionService portalCompanyPositionService;
	
	


	/**
	 * 企业用户列表分页查询
	 * 
	 * @param request
	 * @param response
	 * @param page
	 *            当前页
	 * @param rows
	 *            每页显示记录数
	 * @param sidx
	 *            排序字段
	 * @param sord
	 *            排序方式
	 * @return
	 * @throws JSONException
	 */
	@ApiOperation(value="分页查询用户列表")
	@RequestMapping(value = "/user/list",method= RequestMethod.POST)
	public @ResponseBody ResultBean userList(HttpServletRequest request, HttpServletResponse response,
			@RequestBody @ApiParam(value = "查询用户的查询条件")PortalCompanyUserQueryBean bean) {
		Pagination<PortalCompanyUser> pager = super.initPager(bean.getStart() / bean.getLength() + 1, bean.getLength(),
				bean.getOrderBy(), bean.getSort());
		ResultBean result = new ResultBean(true, null);
		try {
			if (!StringUtil.isEmpty(bean.getUsername())) {
				bean.setUsername(bean.getUsername().trim());
			}
			result.setObject(portalCompanyUserService.queryPageUserList(pager, bean.getUsername(), bean.getEmail(),
					bean.getPhone()));
		} catch (Exception e) {
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}
		return result;
	}
	
	
	/**
	 * 高级搜索
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/user/advanced",method= RequestMethod.POST)
	public @ResponseBody ResultBean getAdvancedSearch(HttpServletRequest request,HttpServletResponse response
			,@RequestBody PortalCompanyUserReporttoTreeDto thisDto
			){
		ResultBean result=new ResultBean(true,"");
		
		List<PortalCompanyUserReporttoTreeDto>  data = portalCompanyUserService.getAdvancedSearch(thisDto);
//		
		result.setObject(data);
		return result;
	}
	
	
	
	
	/**
	 * 企业用户列表分页查询
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/user/listlevel",method= RequestMethod.POST)
	public @ResponseBody ResultBean getLowerList(HttpServletRequest request,HttpServletResponse response
			,@RequestBody PortalCompanyUserReporttoTreeDto thisDto
			){
		ResultBean result=new ResultBean(true,"");

		List<PortalCompanyUserReporttoTreeDto>  data = portalCompanyUserService.getUserListByCondition(thisDto);

		result.setObject(data);
		return result;
	}
	
	

	

	/**
	 * 用户修改自己的密码
	 * 
	 * @Date : 2016-7-5
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/user/changeMyPwd",method= RequestMethod.POST)
	public @ResponseBody ResultBean changeMyPwd(HttpServletRequest request, @RequestBody Map<String, String> map) {
		ResultBean result = new ResultBean(true, null);
		String newPassword = null;
		String newPasswordConfirm = null;
		if (map.containsKey("newPassword")) {
			newPassword = map.get("newPassword");
		}
		if (map.containsKey("newPasswordConfirm")) {
			newPasswordConfirm = map.get("newPasswordConfirm");
		}
		try {
			if (!newPassword.equals(newPasswordConfirm)) {// 两次密码不一致
				throw new ServiceException(ResultStatus.PARAM_ERROR.getCode());
			}
			portalCompanyUserService.changeMyPassword(newPassword);
		} catch (ServiceException e) {
		
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}
		return result;
	}

	/**
	 * 管理员修改用户密码
	 * 
	 * @Date : 2016-6-30
	 * @param username
	 * @param newPassword
	 * @return
	 */
	@RequestMapping(value = "/user/resetPwd",method= RequestMethod.POST)
	public @ResponseBody ResultBean changePwd(HttpServletRequest request, @RequestBody PortalCompanyUserBean bean) {
		ResultBean result = new ResultBean(true, null);
		try {
			if (!bean.getPwd().equals(bean.getConPwd())) {// 两次密码不一致
				throw new ServiceException(ResultStatus.PARAM_ERROR.getCode());
			}
			logger.cacheLog(Level.INFO, "", "Uses_Operations用户"+SpringWebUtils.getRequestUser()+",修改了"+bean.getUsername()+"的密码");
			portalCompanyUserService.changePassword(bean.getUsername(), bean.getPwd());
		} catch (Exception e) {
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}

		return result;
	}

	/**
	 * 企业用户编辑
	 * 
	 * @param request
	 * @param response
	 * @param portalCompanyUser
	 * @return
	 */
	@ApiOperation(value="编辑企业用户")
	@RequestMapping(value = "/user/edit",method= RequestMethod.POST)
	public @ResponseBody ResultBean userEdit(HttpServletRequest request, HttpServletResponse response,
			@RequestBody @ApiParam(value = "用户信息")PortalCompanyUserAddEditBean portalCompanyUser) {
		ResultBean result = new ResultBean(true, null);
		try {
			if (!checkEmail(portalCompanyUser.getEmail())) {
				throw new ServiceException("邮箱格式错误");
			}
			if (!isMobileNO(portalCompanyUser.getPhone())) {
				throw new ServiceException("手机格式错误");
			}
			logger.cacheLog(Level.INFO, "", "Uses_Operations用户"+SpringWebUtils.getRequestUser()+",修改了"+portalCompanyUser.getUsername()+"的基本信息");
			portalCompanyUserService.updateCompanyUser(portalCompanyUser);
		} catch (Exception e) {
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}
		return result;
	}

	/**
	 * 企业用户新增
	 * 
	 * @param request
	 * @param response
	 * @param portalCompanyUser
	 * @return
	 */
	@ApiOperation(value="新增企业用户")
	@RequestMapping(value = "/user/add",method= RequestMethod.POST)
	public @ResponseBody ResultBean userAdd(HttpServletRequest request, HttpServletResponse response,
			@RequestBody @ApiParam(value = "用户信息")PortalCompanyUserAddEditBean portalCompanyUser) {
		ResultBean result = new ResultBean(true, null);
		try {
			if (!checkEmail(portalCompanyUser.getEmail())) {
				throw new ServiceException("邮箱格式错误");
			}
			if (!isMobileNO(portalCompanyUser.getPhone())) {
				throw new ServiceException("手机格式错误");
			}
			/*
			 * if(!pwd.equals(conPwd)){//两次密码不一致 throw new
			 * ServiceException(CommonErrorCodes.CODE_PARAM_ERROR); }
			 */
			portalCompanyUserService.insertCompanyUser(portalCompanyUser, portalCompanyUser.getPwd());
			portalCompanyUser.setPwd(null);
			logger.cacheLog(Level.INFO, new JSONObject(portalCompanyUser).toString(), "Uses_Operations用户"+SpringWebUtils.getRequestUser()+"新增了用户"+portalCompanyUser.getUsername());
		} catch (Exception e) {
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}

		return result;
	}
	
	@ApiOperation(value="编辑企业用户时获取用户明细")
	@RequestMapping(value = "/user/editByDetail",method= RequestMethod.POST)
	public @ResponseBody TResultBean<PortalCompanyUserAddEditBean> queryEditUser(@RequestBody @ApiParam(value = "用户信息")
		PortalCompanyUserAddEditBean portalCompanyUser){
		TResultBean<PortalCompanyUserAddEditBean> result = 
				new TResultBean<PortalCompanyUserAddEditBean>(true, portalCompanyUserService.queryEditDetailUser(portalCompanyUser));
		return result;
	}
	

	/**
	 * 企业用户删除
	 * 
	 * @param userId
	 * @return
	 */
	@ApiOperation(value="批量删除用户")
	@RequestMapping(value = "/user/del",method= RequestMethod.POST)
	public @ResponseBody ResultBean roleDel(HttpServletRequest request, @RequestBody @ApiParam(value = "参数为：portalCompanyUserIds:[1,2..]")Map<String, Object> map) {
		
		ResultBean result = new ResultBean(true, null);
		try {
			ArrayList<Integer> ids = null;
			if (map.containsKey("portalCompanyUserIds")) {
				ids = (ArrayList<Integer>) map.get("portalCompanyUserIds");
				portalCompanyUserService.deleteUsers(ids);
			}
		} catch (Exception e) {
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}
		return result;
	}
	
	
	/**
	 * 企业用户明细查询
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/user/detail",method= RequestMethod.POST)
	public @ResponseBody ResultBean userDetail(HttpServletRequest request, @RequestBody PortalCompanyUserBean bean) {
		
		ResultBean result = new ResultBean(true, null);
		try {
			result.setObject(portalCompanyUserService.queryUserDetail(Integer.parseInt(bean.getPortalCompanyUserId().toString())));
			
		} catch (Exception e) {
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}
		return result;
	}

	/**
	 * 查询用户未分配的角色和已分配的角色
	 * 
	 * @return
	 */
	@RequestMapping(value = "/user/towWayRoles",method= RequestMethod.POST)
	public @ResponseBody ResultBean assignPurviewPage(

			@RequestBody PortalCompanyUserBean bean) {

		ResultBean result = new ResultBean(true, null);
		try {
			// 当前企业用户拥有的角色权限
			List<PortalCompanyRole> userHasRoleList = portalCompanyUserService.queryUserHasRoleList(bean.getUsername(),
					bean.getCompanyCode());
			// 当前企业用户未拥有的角色权限
			Map<String, Object> model = new HashMap<>();
			List<PortalCompanyRole> userNotHasRoleList = portalCompanyUserService
					.queryUserNotHasRoleList(bean.getUsername(), bean.getCompanyCode());
			model.put("username", bean.getUsername());
			model.put("userHasRoleList", userHasRoleList);
			model.put("userNotHasRoleList", userNotHasRoleList);
			result.setObject(model);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}

		return result;
	}

	/**
	 * 保存用户角色权限
	 * 
	 * @Date : 2016-6-12
	 * @param username
	 * @param portalCompanyRoleIds
	 * @return
	 */
	@RequestMapping(value = "/user/saveRole",method= RequestMethod.POST)
	public @ResponseBody ResultBean savePurview(@RequestBody PortalCompanyUserRoleBean portalCompanyUserRoleBean) {
		ResultBean result = new ResultBean(true, null);
		try {
			Long[] portalCompanyRoleIds = (Long[]) portalCompanyUserRoleBean.getPortalCompanyRoleIds()
					.toArray(new Long[portalCompanyUserRoleBean.getPortalCompanyRoleIds().size()]);
			portalCompanyUserService.saveUserRole(portalCompanyUserRoleBean.getUsername(), portalCompanyRoleIds,
					portalCompanyUserRoleBean.getCompanyCode());
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}

		return result;
	}
	/**
	 * 
	    * @Title: saveUserByRole
	    * @Description: 给角色添加成员
	    * @param @return    参数
	    * @return ResultBean    返回类型
	    * @throws
	 */
	@ApiOperation(value="给角色添加成员")
	@RequestMapping(value = "/user/addUserByRole",method= RequestMethod.POST)
	public @ResponseBody ResultBean saveUserByRole(@RequestBody PortalCompanyRoleAddUserBean bean){
		List<String> usernames = bean.getUsername();
		portalCompanyUserService.saveUserByRole(usernames, 
				bean.getPortalCompanyRoleId(), SpringWebUtils.getRequestCompany());
		return new ResultBean(true);
	}
	
	@ApiOperation(value="角色下批量移除成员")
	@RequestMapping(value = "/user/removeUserByRole",method= RequestMethod.POST)
	public @ResponseBody ResultBean removeUserByRole(@RequestBody PortalCompanyRoleAddUserBean bean){
		List<String> usernames = bean.getUsername();
		portalCompanyUserService.removeUserByRole(usernames,
				bean.getPortalCompanyRoleId(), SpringWebUtils.getRequestCompany());
		return new ResultBean(true);
	}
	

	/**
	 * 通过企业code查询用户
	 * 
	 * @Date : 2016-6-24
	 * @return
	 */
	@RequestMapping(value = "/user/findByCompany",method= RequestMethod.POST)
	public @ResponseBody List<PortalCompanyUser> queryListByCompany(
			@RequestParam(required = false) String companyCode) {
		List<PortalCompanyUser> list = portalCompanyUserService.queryListByCompany(companyCode);
		return list;
	}

	public static boolean checkEmail(String email) {// 验证邮箱的正则表达式
		String format = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		// p{Alpha}:内容是必选的，和字母字符[\p{Lower}\p{Upper}]等价。如：200896@163.com不是合法的。
		// w{2,15}: 2~15个[a-zA-Z_0-9]字符；w{}内容是必选的。 如：dyh@152.com是合法的。
		// [a-z0-9]{3,}：至少三个[a-z0-9]字符,[]内的是必选的；如：dyh200896@16.com是不合法的。
		// [.]:'.'号时必选的； 如：dyh200896@163com是不合法的。
		// p{Lower}{2,}小写字母，两个以上。如：dyh200896@163.c是不合法的。
		if (email.matches(format)) {
			return true;// 邮箱名合法，返回true
		} else {
			return false;// 邮箱名不合法，返回false
		}
	}

	public static boolean isMobileNO(String mobiles) {

		Pattern p = Pattern.compile("^(1[0-9])\\d{9}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	/**
	 * 根据角色id列表查询用户
	 * 
	 * @param map
	 * @return ResultBean
	 * @Author Administrator
	 * @Date 2017年9月25日
	 */
	@ApiOperation(value="根据角色集合查询用户")
	@RequestMapping(value = "/user/findByRole",method= RequestMethod.POST)
	public @ResponseBody TResultBean<List<PortalCompanyUserBean>> queryUsersByRole(HttpServletRequest request, HttpServletResponse response,
			@RequestBody @ApiParam(value = "参数为：roleIds:[1,2..]")Map<String, Object> map) {
		ArrayList<Integer> ids = null;
		if (map.containsKey("roleIds")) {
			ids = (ArrayList<Integer>) map.get("roleIds");
		}
		TResultBean<List<PortalCompanyUserBean>> result = 
				new TResultBean<List<PortalCompanyUserBean>>(true, portalCompanyUserService.queryUserInfoBy(ids, 0));
		return result;

	}

	/**
	 * 根据级别查询用户
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return ResultBean
	 * @Author Administrator
	 * @Date 2017年9月25日
	 */
	@RequestMapping(value = "/user/findBylevel",method= RequestMethod.POST)
	public @ResponseBody ResultBean queryUsersByLevel(HttpServletRequest request, HttpServletResponse response,
			@RequestBody Map<String, Object> map) {
		ResultBean result = new ResultBean(true, null);
		try {
			ArrayList<Integer> ids = null;
			if (map.containsKey("levelIds")) {
				ids = (ArrayList<Integer>) map.get("levelIds");
			}
			result.setObject(portalCompanyUserService.queryUserInfoBy(ids, 1));
		} catch (Exception e) {
			result.setSuccess(false);
			e.printStackTrace();
		}
		return result;

	}

	/**
	 * 根据组织查询用户
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return ResultBean
	 * @Author Administrator
	 * @Date 2017年9月25日
	 */
	@RequestMapping(value = "/user/findByOrg",method= RequestMethod.POST)
	public @ResponseBody ResultBean queryUsersByOrgs(HttpServletRequest request, HttpServletResponse response,
			@RequestBody Map<String, Object> map) {
		ResultBean result = new ResultBean(true, null);
		try {
			ArrayList<Integer> ids = null;
			if (map.containsKey("orgIds")) {
				ids = (ArrayList<Integer>) map.get("orgIds");
			}
			result.setObject(portalCompanyUserService.queryUserInfoBy(ids, 2));
		} catch (Exception e) {
			result.setSuccess(false);
			e.printStackTrace();
		}
		return result;

	}

	/**
	 * 根据组织查询用户
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return ResultBean
	 * @Author Administrator
	 * @Date 2017年9月25日
	 */
	@RequestMapping(value = "/user/findByPosition",method= RequestMethod.POST)
	public @ResponseBody ResultBean queryUsersByPosition(HttpServletRequest request, HttpServletResponse response,
			@RequestBody Map<String, Object> map) {
		ResultBean result = new ResultBean(true, null);
		try {
			ArrayList<Integer> ids = null;
			if (map.containsKey("positionIds")) {
				ids = (ArrayList<Integer>) map.get("positionIds");
			}
			result.setObject(portalCompanyUserService.queryUserInfoBy(ids, 3));
		} catch (Exception e) {
			result.setSuccess(false);
			e.printStackTrace();
		}
		return result;

	}

	/**
	 * 根据其他条件查询用户
	 * 
	 * @param request
	 * @param response
	 * @param bean
	 * @return ResultBean
	 * @Author Administrator
	 * @Date 2017年9月25日
	 */
	@RequestMapping(value = "/user/findByCondition",method= RequestMethod.POST)
	public @ResponseBody ResultBean queryUsersByCondition(HttpServletRequest request, HttpServletResponse response,
			@RequestBody PortalCompanyUserQueryBean bean) {
		ResultBean result = new ResultBean(true, null);
		try {
            List<PortalCompanyUserBean> portalCompanyUserBeans = portalCompanyUserService.queryUserInfoByConditions(bean) ;
            removeDuplicate(portalCompanyUserBeans);
			result.setObject(portalCompanyUserBeans);
		} catch (Exception e) {
			result.setSuccess(false);
			e.printStackTrace();
		}
		return result;

	}

	/**
	 * 根据用户id列表查询用户信息
	 * @param request
	 * @param response
	 * @param map
	 * @return ResultBean
	 * @Author Administrator
	 * @Date 2017年9月27日
	 */
	@RequestMapping(value = "/user/findByIds",method= RequestMethod.POST)
	public @ResponseBody ResultBean queryUsersByUserIds(HttpServletRequest request, HttpServletResponse response,
			@RequestBody Map<String, Object> map) {
		ResultBean result = new ResultBean(true, null);
		ArrayList<Integer> ids = null;
		if (map.containsKey("userIds")) {
			ids = (ArrayList<Integer>) map.get("userIds");
		}
		try {
			result.setObject(portalCompanyUserService.queryUserInfoBy(ids, 4));
		} catch (Exception e) {
			result.setSuccess(false);
			e.printStackTrace();
		}
		return result;

	}


    public  List removeDuplicate(List list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }
}
